package io.github.ramerf.wind.core.handler.typehandler;

import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.sql.PreparedStatement;

/**
 * {@literal java:Boolean <=> jdbc:Integer}.
 *
 * @since 2022.09.12
 * @author ramer
 */
public class BooleanToIntegerTypeHandler implements ITypeHandler<Boolean, Integer> {
  @Override
  public Object convertToJdbc(
      final Boolean javaVal, final Field field, @Nonnull final PreparedStatement ps) {
    if (field.getType().equals(boolean.class)) {
      return javaVal == null || !javaVal ? 0 : 1;
    }
    return javaVal == null ? null : javaVal ? 1 : 0;
  }

  @Override
  public Boolean convertFromJdbc(
      final Integer jdbcVal, final Object defaultValue, final Field field) {
    return jdbcVal != null ? jdbcVal > 0 : null;
  }
}
